<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <!-- 一===学科名称那一行 -->
        <el-form :inline="true" ref="query" :model="query" label-width="80px">
          <span>
            <el-form-item label="学科名称">
              <el-input v-model="query.subjectName"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="clearFn">清除</el-button>
            </el-form-item>
            <el-button type="primary" @click="seachFn(query.subjectName)"
              >搜索</el-button
            >
          </span>
          <span>
            <el-button type="success" icon="el-icon-edit" @click="addFn"
              >新增学科</el-button
            ></span
          >
        </el-form>
        <!--二=== 数据一共xx条 -->
        <el-row>
          <el-col :span="24">
            <span class="el-alert__icon el-icon-info"></span>
            <span class="text">数据一共{{ counts }} 条</span>
            <div class="grid-content bg-purple-dark"></div
          ></el-col>
        </el-row>
        <!-- 三=== 表单 -->
        <el-table :data="items" style="width: 100%" min-width>
          <el-table-column type="index" label="序号"> </el-table-column>
          <el-table-column prop="subjectName" label="学科名称">
          </el-table-column>
          <el-table-column prop="username" label="创建者"> </el-table-column>
          <el-table-column prop="addDate" label="创建日期" width="200px">
            <!-- 格式化入职时间 -->
            <template v-slot="scope">
              <!-- 管道运算符 {{ scope.row.addDate | 管道运算符的名称}} -->
              <span>{{ scope.row.addDate | formAddTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="前台是否显示">
            <template slot-scope="scope">
              <!--  === 'true' ? '显示' : '不显示'" label="前台是否显示 -->
              <span v-if="scope.row.isFrontDisplay === 0">否</span>
              <span v-else-if="scope.row.isFrontDisplay === 1">是</span>
            </template>
          </el-table-column>
          <el-table-column prop="twoLevelDirectory" label="二级目录">
          </el-table-column>
          <el-table-column prop="tags" label="标签"> </el-table-column>
          <el-table-column prop="totals" label="题目数量"> </el-table-column>
          <el-table-column fixed="right" label="操作" width="220">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="directorysFn(scope.row)">学科分类</el-button>
              <el-button type="text" size="small" @click="tagsFn(scope.row)">学科标签</el-button>
              <el-button type="text" size="small" @click="editFn(scope.row)"
                >修改</el-button
              >
              <el-button
                @click.native.prevent="deleteRow(scope.row)"
                type="text"
                size="small"
              >
                删除
              </el-button>
              <el-dialog
                :title="isEdit ? '修改学科' : '新增学科'"
                :visible.sync="dialogVisible"
                width="30%"
                :modal="false"
                @close="closeFn"
              >
                <el-form ref="subjectForm" :model="subjectForm" :rules="rules">
                  <el-form-item label="学科名称" prop="subjectName">
                    <el-input v-model="subjectForm.subjectName"></el-input>
                  </el-form-item>
                  <el-form-item label="是否显示">
                    <el-switch
                      v-model="subjectForm.isFrontDisplay"
                      active-value="1"
                      inactive-value="0"
                    ></el-switch>
                  </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                  <el-button @click="cancelDoFn">取 消</el-button>
                  <el-button type="primary" @click="sureDoFn">确 定</el-button>
                </span>
              </el-dialog>
            </template>
          </el-table-column>
        </el-table>
        <!-- 四=== 分页 -->
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="query.size"
            layout="prev, pager, next, sizes, jumper"
            background
            :total="counts"
          >
          </el-pagination>
        </div>
      </el-card>
    </div>
  </div>
</template>
<script>
import { list, update, add, remove } from '@/api/hmmm/subjects'
import dayjs from 'dayjs'
export default {
  name: 'subjects',
  data () {
    return {
      items: [] /* 后台获取的数据数组 */,
      counts: 1 /* 总数据量 */,
      subjetId: '' /* 点击的数据的ID */,
      dialogVisible: false /* 编辑的弹框默认关闭 */,
      isEdit: false,
      // isFrontDisplay: 0,
      subjectForm: {
        subjectName: '',
        isFrontDisplay: '1'
      },
      // 搜索的表单
      query: {
        page: 1, // 当前页面
        pagesize: 10, // 页面显示的条数
        subjectName: '' /* 搜索的学科名称 */
      },
      rules: {
        subjectName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          {
            min: 1,
            max: 10,
            message: '长度在 1 到 10 个字符',
            trigger: 'blur'
          }
        ]
      }
      // form: {
      //   name: ''
      // }
    }
  },
  created () {
    this.getList()
  },
  // 格式化时间
  filters: {
    // 过滤器方法的形参是需要格式化的数据
    // 就是管道运算符左侧的数据
    formAddTime (value) {
      // 内部必须有返回值
      // console.log(value)
      return dayjs(value).format('YYYY-MM-DD hh:mm:ss')
    }
  },
  methods: {
    // 1.删除
    async deleteRow (id) {
      console.log(this.items.length)
      // console.log(id)
      // 显示删除询问对话框
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await remove(id)
          console.log(res)
          // 判断当前数据的长度是否等于 1
          if (this.items.length === 1) {
            this.query.page--
            // 如果是第一页的第一条
            if (this.query.page <= 0) {
              this.query.page = 1
            }
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          // 重新获取数据
          this.getList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 2. 分页
    // 每页显示的条数发生改变时触发
    handleSizeChange (newSize) {
      this.query.pagesize = newSize
      this.getList()
    },
    handleCurrentChange (newPage) {
      this.query.page = newPage
      this.getList()
    },
    // 3.获取所有列表
    async getList () {
      const res = await list(this.query)
      // console.log(res)
      // 根据返回的状态码进行业务处理
      if (res.request.status !== 200) {
        return this.$message.error('获取列表失败')
      }
      this.items = res.data.items
      this.counts = res.data.counts
      // console.log(this.items)
    },
    // 4.点击修改row行对行
    async editFn (row) {
      const edit = {}
      Object.assign(edit, row)
      this.subjectForm = edit
      if (this.subjectForm.isFrontDisplay === 1) {
        this.subjectForm.isFrontDisplay = '1'
      } else if (this.subjectForm.isFrontDisplay === 0) {
        this.subjectForm.isFrontDisplay = '0'
      }
      this.isEdit = true
      // if (!res.success) return this.$message.error(res.message)
      this.dialogVisible = true
    },
    // 5.新增学科
    async addFn () {
      this.isEdit = false
      this.dialogVisible = true
    },
    // 6.确定
    sureDoFn () {
      this.$refs.subjectForm.validate(async (valid) => {
        if (valid) {
          if (!this.isEdit) {
            // 调用添加的 API
            const res = await add(this.subjectForm)
            // 根据状态码判断请求成功与否
            // 添加成功，给用户进行提示
            if (res.request.status === 200) {
              // 隐藏弹框
              this.dialogVisible = false
              // 清空subjectForm里的 subjectName，点新增的时候不会有上次的值
              // this.subjectForm.subjectName = ''
            }
          } else {
            // 调用编辑的 API
            const res = await update(this.subjectForm)
            // 根据状态码判断请求成功与否
            // 编辑成功，给用户进行提示
            if (res.request.status === 200) {
              this.$message.success('操作成功')
              // 隐藏弹框
              this.dialogVisible = false
            } else {
              this.$message.error('操作失败，请重新输入')
            }
          }
        }
        // 重新获取权限列表数据
        this.getList()
        // console.log(this.subjectForm.subjectName)
        // 清空subjectForm里的 subjectName，点新增的时候不会有上次的值
        setTimeout(() => {
          this.subjectForm.subjectName = ''
        }, 0)
        // console.log(this.subjectForm.subjectName)
      })
    },
    // 7. 点击弹框的x
    closeFn () {
      // 清空subjectForm里的 subjectName，点新增的时候不会有上次的值
      setTimeout(() => {
        this.subjectForm.subjectName = ''
      }, 0)
    },
    // 7.取消
    cancelDoFn () {
      this.dialogVisible = false
      // 清空subjectForm里的 subjectName，点新增的时候不会有上次的值
      this.subjectForm.subjectName = ''
    },
    // 8.查找,搜索---点击搜索
    async seachFn (val) {
      const res = await list(this.query)
      this.items = res.data.items
      this.counts = res.data.counts
    },
    // 9. 搜索---点击清除按钮
    clearFn () {
      this.query.subjectName = ''
    },
    // 10.点击学科分类--进入目录--调接口，路由跳转
    async directorysFn (row) {
      /* const res = await directorys(this.subjetId)
      console.log(res)
      this.$router.push('/subjects/directorys') */
      this.$router.push('/subjects/directorys?id=' + row.id + '&name=' + row.subjectName)
    },
    // 11.// 点击学科标签
    async tagsFn (row) {
      // const res = await list(this.items)
      // console.log(res)
      // location.href = "#/subjects/tags?id="+row.id+"&name="+row.subjectName
      this.$router.push('/subjects/tags?id=' + row.id + '&name=' + row.subjectName)
    }
  }
}
</script>

<style scoped>
/* /deep/.el-input__inner {
  width: 200px;
} */
.el-form--inline {
  display: flex;
  justify-content: space-between;
}
.el-col-24 {
  background: #d3dce6;
  border-radius: 4px;
  height: 30px;
  line-height: 25px;
  margin-bottom: 20px;
}
.el-col.el-col-24 {
  padding-left: 30px;
  color: #403333;
  line-height: 30px;
  font-size: 15px;
}
.el-form {
  padding-left: 0px;
}
.text {
  margin-left: 20px;
}
.block {
  margin-top: 20px;
  float: right;
}
.el-card.is-never-shadow {
  padding-bottom: 50px;
}
::v-/deep/.el-dialog__footer {
  text-align: right;
}
::v-/deep/.el-dialog__body {
  padding: 10px 20px;
}
::v-/deep/.el-card__body {
  padding: 20px;
}
</style>
